// components/uploadFile/uploadFile.js
const app = getApp();
Component({
  options: {
    multipleSlots: true, //多slot支持
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    max: {
      type: Number,
      value: 1
    },
    imgList: {
      type: Array,
      value: []
    },
    fileType: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    modalName: null,
    ITEM_SIZE: 100, // 图片大小 单位px
    dragImgList: [], // 图片列表 { src: string, key: number, tranX: number, tranY: number }[]
    containerRes: {}, // 拖拽容器属性
    currentKey: -1, // 正在拖拽图片的key
    currentIndex: -1, // 正在拖拽图片的index
    tranX: 0, // 正在拖拽图片移动的x距离
    tranY: 0, // 正在拖拽图片移动的y距离
    uploadPosition: { // upload上传图标位移距离
      tranX: 0,
      tranY: 0,
    }
  },

  /**
   * 组件的方法列表
   */
  lifetimes: {
    ready() {
      this.createSelectorQuery()
        .select(".drag-container")
        .boundingClientRect((res) => {
          this.data.containerRes = res
        }).exec();
    }
  },
  methods: {
    ViewImage(e) {
      wx.previewImage({
        urls: this.data.imgList,
        current: e.currentTarget.dataset.url
      });
    },
      /**
     * 长按图片
     */
    longPress(e) {
      const index = e.mark.index
      const { pageX, pageY } = e.touches[0]
      const { top, left } = this.data.containerRes
      this.setData({
        currentIndex: index,
        tranX: pageX - 50 - left,
        tranY: pageY - 50 - top
      })
    },
     /**
     * touchMove
     */
    touchMove(e) {
      // 如果currentIndex < 0，说明并没有触发longPress
      if (this.data.currentIndex < 0) return
      const { pageX, pageY } = e.touches[0]
      const { top, left } = this.data.containerRes
      const tranX = pageX - 50 - left
      const tranY = pageY - 50 - top
      this.setData({
        tranX,
        tranY
      })
      // 对比当前移动的key和停放位置的key，如果不一样就修改位置
      const currentKey = e.mark.key
      const moveKey = this.getMoveKey(tranX, tranY)
      // console.log(currentKey, moveKey);
      if (currentKey === moveKey || this.data.currentKey === currentKey) return
      this.data.currentKey = currentKey
      this.insert(currentKey, moveKey)
    },
      /**
     * 获取移动中的key
     */
    getMoveKey(tranX, tranY) {
      const { dragImgList: list, ITEM_SIZE } = this.data
      const _getPositionNumber = (drag) => {
        const positionNumber = Math.round(drag / ITEM_SIZE)
        return positionNumber > 2 ? 2 : positionNumber < 0 ? 0 : positionNumber
      }
      const endKey = 3 * _getPositionNumber(tranY) + _getPositionNumber(tranX)
      return endKey >= list.length ? list.length - 1 : endKey
    },
      /**
     * 处理移动中key的变化
     */
    insert(origin, end) {
      const dragImgList = this.data.dragImgList
      dragImgList.forEach((item) => {
        if (origin < end) {
          if (item.key > origin && item.key <= end) item.key--
          else if (item.key === origin) item.key = end
        } else if (origin > end) {
          if (item.key >= end && item.key < origin) item.key++
          else if (item.key === origin) item.key = end
        }
      })
      this.getListPosition(dragImgList)
    },
      /**
     * 修改位置
     */
    getListPosition(list) {
      const ITEM_SIZE = this.data.ITEM_SIZE
      const dragImgList = list.map((item) => {
        item.tranX = ITEM_SIZE * (item.key % 3);
        item.tranY = Math.floor(item.key / 3) * ITEM_SIZE;
        return item
      })
      this.setData({
        dragImgList,
      })

      const srcList = [...dragImgList].sort((a, b) => a.key - b.key).map((item) => item.src)
      this.triggerEvent('updateImage', {
        list: srcList
      })
    },
        /**
     * touchEnd
     */
    touchEnd() {
      this.setData({
        tranX: 0,
        tranY: 0,
        currentIndex: -1,
      })
      this.data.currentKey = -1
    },
  /**
     * 修改上传图标位置
     */
    setUploaPosition(listLength) {
      const ITEM_SIZE = this.data.ITEM_SIZE
      const uploadPosition = {
        tranX: listLength % 3 * ITEM_SIZE,
        tranY: Math.floor(listLength / 3) * ITEM_SIZE,
      }
      this.setData({
        uploadPosition,
      })
    },
    ChooseImageByxiangji() {
      this.hideModal();
      let self = this;
      wx.chooseImage({
        count: self.data.max, //默认1
        sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera'],
        success: (res) => {
          console.log('微信回调', res);
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            });
            this.uploadTheImage();
          } else {
            this.setData({
              imgList: res.tempFilePaths
            })
            this.uploadTheImage();
          }
        }
      });
    },
    ChooseImageByxiangce() {
      this.hideModal();
      let self = this;
      wx.chooseImage({
        count: self.data.max, //默认1
        sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'],
        success: (res) => {
          console.log('微信回调', res);
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            })
            this.uploadTheImage();
          } else {
            this.setData({
              imgList: res.tempFilePaths
            })
            this.uploadTheImage();
          }
        }
      });
    },
    ChooseImage() {
      this.hideModal();
      let self = this;
      wx.chooseImage({
        count: self.data.max, //默认1
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'],
        success: (res) => {
          console.log('微信回调', res);
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            })
          } else {
            this.setData({
              imgList: res.tempFilePaths
            })
          }
        }
      });
    },
    chooseMessageFile() {
      this.hideModal();
      let self = this;
      wx.chooseMessageFile({
        count: self.data.max - self.data.imgList.length, //默认1
        type: 'image',
        success: (res) => {
          console.log('微信回调', res);
          res.tempFilePaths = [];
          res.tempFiles.forEach(item => {
            res.tempFilePaths.push(item.path);
          })
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            })
            this.uploadTheImage();
          } else {
            this.setData({
              imgList: res.tempFilePaths
            })
            this.uploadTheImage();
          }
        }
      });
    },
    uploadTheImage() {
      let imgList = this.data.imgList;
      imgList.forEach(async (filePath, index) => {
        if (filePath.indexOf('tmp') != -1 || filePath.indexOf('wxfile') != -1) {
          // 压缩一下再上传
          if (filePath.substring(filePath.length - 3) == 'jpg') {
            const compressImage = app.promisify(wx.compressImage);
            console.log(filePath);
            const res = await compressImage({
              src: filePath, // 图片路径
              quality: 67 // 压缩质量
            });
            filePath = res.tempFilePath;
          }
          let self = this;
          app.sHttp.upload({
            'filePath': filePath,
            'fileType': this.data.fileType || 'carArchives',
            'isNeedThumbnail': 0
          }).then(res => {
            imgList[index] = res.originalUrl;
            self.setData({
              imgList: imgList
            })
          }, err => {
            app.error(err.msg);
          })
        }
      })
    },
    doNothing() {},
    hideModal(e) {
      this.setData({
        modalName: null,
      })
    },
    showModal() {
      this.setData({
        modalName: 'typeChoose'
      })
    },
    DelImg(e) {
      wx.showModal({
        title: '删除确认',
        content: '确定要删除这张图片嘛？',
        cancelText: '取消',
        confirmText: '删除',
        success: res => {
          if (res.confirm) {
            this.data.imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              imgList: this.data.imgList
            })
          }
        }
      })
    },
    // 上传方法
    // carArchives	车辆档案
    // banner	轮播图
    // dealerLogo	车商logo
    // dealerData	车商资料图
    // custmagerLogo	客户经理logo
    // custmagerQrcode	客户经理二维码
    // dealerUserLogo	车商用户logo
    uploadFiles(fileType, isNeedThumbnail, canZero) {
      if (this.data.imgList.length == 0) {
        return new Promise(function (resolve, reject) {
          if (true == canZero) {
            resolve([]);
          } else {
            reject('请选择图片');
          }
        })
      } else {
        let ImgList = this.data.imgList;
        let promiseList = [];
        app.showLoading('提交中');
        let noUploadReq = [];
        ImgList.forEach(filePath => {
          if (filePath.indexOf('tmp') != -1 || filePath.indexOf('wxfile') != -1) {
            promiseList.push(app.sHttp.upload({
              'filePath': filePath,
              'fileType': fileType,
              'isNeedThumbnail': isNeedThumbnail
            }));
          } else {
            noUploadReq.push(filePath);
          }
        });
        return new Promise(function (resolve, reject) {
          if (promiseList.length > 0) {
            Promise.all(promiseList).then((result) => {
              noUploadReq.forEach(item => {
                result.push({
                  originalUrl: item
                });
              });
              wx.hideLoading();
              resolve(result)
            }).catch((error) => {
              wx.hideLoading();
              reject(error)
            })
          } else {
            wx.hideLoading();
            let result = [];
            noUploadReq.forEach(item => {
              result.push({
                originalUrl: item
              });
            });
            resolve(result)
          }
        })
      }
    },

  }
})